package com.chexiehui.jc.ui.fragment;

import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.SimpleItemAnimator;
import android.view.Gravity;
import android.view.View;
import android.view.animation.AccelerateInterpolator;
import android.widget.TextView;

import com.alibaba.android.vlayout.DelegateAdapter;
import com.alibaba.android.vlayout.VirtualLayoutManager;
import com.alibaba.android.vlayout.layout.LinearLayoutHelper;
import com.alibaba.android.vlayout.layout.SingleLayoutHelper;
import com.aries.ui.view.radius.RadiusTextView;
import com.blankj.utilcode.util.SizeUtils;
import com.blankj.utilcode.util.SpanUtils;
import com.blankj.utilcode.util.StringUtils;
import com.chexiehui.jc.Constants;
import com.chexiehui.jc.R;
import com.chexiehui.jc.adapter.CommVLayoutAdapter;
import com.chexiehui.jc.adapter.HomeBannerAdapter;
import com.chexiehui.jc.base.BaseModel;
import com.chexiehui.jc.base.BaseMvpFragment;
import com.chexiehui.jc.base.BaseMvpLazyLoadFragment;
import com.chexiehui.jc.base.BasePage;
import com.chexiehui.jc.entity.HomeBannerInfo;
import com.chexiehui.jc.entity.PostInfo;
import com.chexiehui.jc.event.GlobalFollowUserEvent;
import com.chexiehui.jc.event.GlobalLikePostEvent;
import com.chexiehui.jc.event.GlobalPostAppraiseEvent;
import com.chexiehui.jc.listener.IHomeRefreshFragment;
import com.chexiehui.jc.mvp.home.HomeSlideRecommendCovenant;
import com.chexiehui.jc.mvp.home.HomeSlideRecommendPresenter;
import com.chexiehui.jc.ui.activity.ForumDynamicDetailsActivity;
import com.chexiehui.jc.ui.activity.ForumTribuneDetailsActivity;
import com.chexiehui.jc.utils.AppCommonUtil;
import com.chexiehui.jc.utils.BundleBuilder;
import com.chexiehui.jc.utils.FixedSpeedScroller;
import com.chexiehui.jc.utils.GlideUtil;
import com.chexiehui.jc.utils.NoDoubleClickListener;
import com.chexiehui.jc.widget.NineGridTestLayout;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.constant.RefreshState;
import com.tmall.ultraviewpager.UltraViewPager;
import com.zhy.adapter.recyclerview.base.ViewHolder;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;

public class HomeSlideRecommendFragment extends BaseMvpLazyLoadFragment<HomeSlideRecommendPresenter> implements HomeSlideRecommendCovenant.View, IHomeRefreshFragment {

    @BindView(R.id.recycler)
    RecyclerView mRecycler;
    @BindView(R.id.refreshLayout)
    SmartRefreshLayout refreshLayout;

    private DelegateAdapter listAdapter;
    private HomeBannerAdapter bannerPagerAdapter;
    private CommVLayoutAdapter<String> bannerAdapter;
    private CommVLayoutAdapter<PostInfo> postAdapter;
    private BasePage<PostInfo> page;
    private List<HomeBannerInfo> bannerData;
    private int position;

    public static HomeSlideRecommendFragment getInstance(int position) {
        HomeSlideRecommendFragment fragment = new HomeSlideRecommendFragment();
        Bundle bundle = new Bundle();
        bundle.putInt("position", position);
        fragment.setArguments(bundle);
        return fragment;
    }

    @Override
    protected boolean isRegisterEventBus() {
        return true;
    }

    @Override
    protected void beforeSetView() {
        Bundle bundle = getArguments();
        if (bundle != null) {
            position = bundle.getInt("position");
        }
    }

    @Override
    protected void initView(Bundle savedInstanceState) {
        refreshLayout.setEnableRefresh(false);
        refreshLayout.setEnableLoadMore(true);
        refreshLayout.setDisableContentWhenLoading(true);
        refreshLayout.setDisableContentWhenRefresh(true);
        refreshLayout.setEnableFooterFollowWhenLoadFinished(false);
        refreshLayout.setEnableLoadMoreWhenContentNotFull(false);
        refreshLayout.setEnableScrollContentWhenRefreshed(true);
        refreshLayout.setOnLoadMoreListener(refreshLayout -> {
            if (page != null && page.getTotalRecordCount() > postAdapter.getData().size()) {
                mvpPresenter.getPostList(page.getPageIndex() + 1);
            } else {
                refreshLayout.finishLoadMoreWithNoMoreData();
            }
        });
        VirtualLayoutManager virtualLayoutManager = new VirtualLayoutManager(mActivity);
        mRecycler.setLayoutManager(virtualLayoutManager);
        final RecyclerView.RecycledViewPool viewPool = new RecyclerView.RecycledViewPool();
        mRecycler.setRecycledViewPool(viewPool);
        ((SimpleItemAnimator)mRecycler.getItemAnimator()).setSupportsChangeAnimations(false);
        mRecycler.getItemAnimator().setChangeDuration(0);
        viewPool.setMaxRecycledViews(0, 20);
        listAdapter = new DelegateAdapter(virtualLayoutManager, false);
        mRecycler.setAdapter(listAdapter);

        int dp_10 = SizeUtils.dp2px(10);

        SingleLayoutHelper bannerLayoutHelper = new SingleLayoutHelper();
        bannerLayoutHelper.setMarginBottom(SizeUtils.dp2px(1));
        bannerLayoutHelper.setBgColor(ContextCompat.getColor(mActivity, R.color.colorWhite));
        bannerData = new ArrayList<>();
        bannerPagerAdapter = new HomeBannerAdapter(bannerData);
        bannerAdapter = new CommVLayoutAdapter<String>(mActivity, new ArrayList<>(), R.layout.item_home_slide_recommend_banner, bannerLayoutHelper) {
            @Override
            public void convert(ViewHolder holder, int position, String item) {
                UltraViewPager ultraViewPager = holder.getView(R.id.ultra_item_banner);
                ultraViewPager.setScrollMode(UltraViewPager.ScrollMode.HORIZONTAL);
                try {
                    Field mField;
                    mField = ViewPager.class.getDeclaredField("mScroller");
                    mField.setAccessible(true);
                    FixedSpeedScroller mScroller =
                            new FixedSpeedScroller(mActivity, new AccelerateInterpolator());
                    mScroller.setmDuration(1000);
                    mField.set(ultraViewPager.getViewPager(), mScroller);
                } catch (Exception e) {
                }
                ultraViewPager.setAutoMeasureHeight(false);
                ultraViewPager.setItemMargin(dp_10, dp_10, dp_10, dp_10);
                ultraViewPager.setAdapter(bannerPagerAdapter);
                //内置indicator初始化
                ultraViewPager.initIndicator();
                //设置indicator样式
                ultraViewPager.getIndicator()
                        .setOrientation(UltraViewPager.Orientation.HORIZONTAL)
                        .setFocusColor(ContextCompat.getColor(mActivity, R.color.colorWhite))
                        .setNormalColor(ContextCompat.getColor(mActivity, R.color.c_999999))
                        .setRadius(SizeUtils.dp2px(5));
                //设置indicator对齐方式
                ultraViewPager.getIndicator().setGravity(Gravity.CENTER_HORIZONTAL | Gravity.BOTTOM);
                ultraViewPager.getIndicator().setMargin(0, 0, 0, SizeUtils.dp2px(15));
                //构造indicator,绑定到UltraViewPager
                ultraViewPager.getIndicator().build();
                //设定页面循环播放
                ultraViewPager.setInfiniteLoop(true);
                //设定页面自动切换  间隔5秒
                ultraViewPager.setAutoScroll(5000);

            }
        };
        listAdapter.addAdapter(bannerAdapter);

        LinearLayoutHelper postHelper = new LinearLayoutHelper(0);
        postHelper.setMarginBottom(dp_10);
        postAdapter = new CommVLayoutAdapter<PostInfo>(mActivity, new ArrayList<>(),
                R.layout.item_forum_post, postHelper) {
            @Override
            public void convert(ViewHolder holder, int position, PostInfo item) {
                holder.getView(R.id.tv_item_forum_name).setOnClickListener(new NoDoubleClickListener() {
                    @Override
                    public void onNoDoubleClick(View view) {
                        startActivity(ForumTribuneDetailsActivity.class, new BundleBuilder()
                                .putString("forumId", item.getForumsId())
                                .create());
                    }
                });
                GlideUtil.loadImageViewCrop(mActivity, item.getAuthorPhoto(), holder.getView(R.id.iv_item_avatar), R.drawable.shape_circle, R.drawable.shape_circle);
                holder.setText(R.id.tv_item_forum_name, item.getForumsName());
                holder.setText(R.id.tv_item_name, item.getAuthorName());
                holder.setText(R.id.tv_item_brief, item.getAuthorRemark());
                TextView tv_item_content = holder.getView(R.id.tv_item_content);
                if (StringUtils.isTrimEmpty(item.getLabel())) {
                    tv_item_content.setText(item.getTitle());
                } else {
                    SpanUtils spanUtils = new SpanUtils();
                    if (item.getLabel().contains("置顶")) {
                        spanUtils.appendImage(R.mipmap.ic_post_zhiding, SpanUtils.ALIGN_BASELINE)
                                .appendSpace(15);
                    }
                    if (item.getLabel().contains("精华")) {
                        spanUtils.appendImage(R.mipmap.ic_post_jinghua, SpanUtils.ALIGN_BASELINE)
                                .appendSpace(15);
                    }
                    spanUtils.append(item.getTitle())
                            .setForegroundColor(ContextCompat.getColor(mActivity, R.color.c_333333))
                            .setBackgroundColor(ContextCompat.getColor(mActivity, R.color.colorWhite));
                    tv_item_content.setText(spanUtils.create());
                }
                holder.setText(R.id.tv_item_time, AppCommonUtil.friendlyTime(item.getCreateTime()));
                holder.setText(R.id.tv_item_appraise_count, item.getCommentNum() + "");
                TextView tv_item_follow_count = holder.getView(R.id.tv_item_follow_count);
                tv_item_follow_count.setText(item.getLikenum() + "");
                Drawable drawable1 = getResources().getDrawable(item.isLike() ? R.mipmap.ic_follow_36_s : R.mipmap.ic_follow_48);
                drawable1.setBounds(0, 0, drawable1.getMinimumWidth(), drawable1.getMinimumHeight());
                tv_item_follow_count.setCompoundDrawables(drawable1, null, null, null);
                RadiusTextView rtv_item_follow_action = holder.getView(R.id.rtv_item_follow_action);
                if (item.getAuthorId().equals(getUserId())) {
                    rtv_item_follow_action.setVisibility(View.GONE);
                } else {
                    rtv_item_follow_action.setVisibility(View.VISIBLE);
                    rtv_item_follow_action.setSelected(item.isFollow());
                    rtv_item_follow_action.setText(item.isFollow() ? "取消关注" : "关注");
                    rtv_item_follow_action.setOnClickListener(new NoDoubleClickListener() {
                        @Override
                        public void onNoDoubleClick(View view) {
                            mvpPresenter.doFollowPerson(item.getAuthorId());
                        }
                    });
                }
                tv_item_follow_count.setOnClickListener(new NoDoubleClickListener() {
                    @Override
                    public void onNoDoubleClick(View view) {
                        mvpPresenter.doDianZan(item.getId());
                    }
                });
                NineGridTestLayout ngtv_item_image_box = holder.getView(R.id.ngtv_item_image_box);
                if (item.getPhotoList().size() > 0) {
                    ngtv_item_image_box.setVisibility(View.VISIBLE);
                    ngtv_item_image_box.setUrlList(item.getPhotoList());
                } else {
                    ngtv_item_image_box.setVisibility(View.GONE);
                }
            }
        };
        postAdapter.setItemClickListener(new CommVLayoutAdapter.OnItemClickListener<PostInfo>() {
            @Override
            public void onItemClick(View view, int position, PostInfo item) {
                startActivity(ForumDynamicDetailsActivity.class, new BundleBuilder()
                        .putString("postId", postAdapter.getData().get(position).getId())
                        .create());
            }
        });
        listAdapter.addAdapter(postAdapter);
        isPrepared = true;
        lazyLoad();
    }

    @Override
    protected void lazyLoad() {
        if(!isVisible || !isPrepared || mHasLoadedOnce){
            return;
        }
        onCallRefresh();
    }

    @Override
    public void onCallRefresh() {
        if(mvpPresenter == null) {
            mvpPresenter = createPresenter();
        };
        mvpPresenter.getBannerInfo();
        mvpPresenter.getPostList(1);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_home_slide_recommend;
    }

    @Override
    protected HomeSlideRecommendPresenter createPresenter() {
        return new HomeSlideRecommendPresenter(this);
    }

    @Override
    public void onGetBannerInfoSuccess(BaseModel<List<HomeBannerInfo>> successResult) {
        mHasLoadedOnce = true;
        bannerAdapter.getData().clear();
        if (successResult.getData() != null && successResult.getData().size() > 0) {
            bannerData.clear();
            bannerData.addAll(successResult.getData());
            bannerAdapter.getData().add("");
        }
        bannerAdapter.notifyDataSetChanged();
    }

    @Override
    public void onGetBannerInfoFailure(BaseModel<Object> failureResult) {
        bannerAdapter.getData().clear();
        bannerAdapter.notifyDataSetChanged();
    }

    @Override
    public void onGetPostListSuccess(BaseModel<BasePage<PostInfo>> successResult) {
        mHasLoadedOnce = true;
        page = successResult.getData();
        if (refreshLayout.getState() == RefreshState.Loading) {
            postAdapter.getData().addAll(page.getItems());
            postAdapter.notifyDataSetChanged();
            if (page.getTotalRecordCount() <= postAdapter.getData().size()) {
                refreshLayout.finishLoadMoreWithNoMoreData();
            } else {
                refreshLayout.finishLoadMore(true);
            }
        } else {
            postAdapter.getData().clear();
            postAdapter.getData().addAll(successResult.getData().getItems());
            postAdapter.notifyDataSetChanged();
        }
    }

    @Override
    public void onGetPostListFailure(BaseModel<Object> failureResult) {
        if (Constants.PAGE_DATA_EMPTY == failureResult.getResultCode()) {
            mHasLoadedOnce = true;
            if (refreshLayout.getState() == RefreshState.Loading) {
                refreshLayout.finishLoadMoreWithNoMoreData();
            }
        } else {
            if (refreshLayout.getState() == RefreshState.Loading) {
                refreshLayout.finishLoadMore(false);
            }
        }
    }

    @Override
    public void onDoDianZanSuccess(BaseModel<String> successResult) {
        for (int i = 0; i < postAdapter.getData().size(); i++) {
            String id = postAdapter.getData().get(i).getId();
            if (id.equals(successResult.getData())) {
                EventBus.getDefault().post(new GlobalLikePostEvent(successResult.getData(), !postAdapter.getData().get(i).isLike()));
                break;
            }
        }
    }

    @Override
    public void onDoDianZanFailure(BaseModel<Object> failureResult) {
        showToast(failureResult.getResultInfo());
    }

    @Override
    public void onDoFollowPersonSuccess(BaseModel<String> successResult) {
        for (int i = 0; i < postAdapter.getData().size(); i++) {
            String id = postAdapter.getData().get(i).getAuthorId();
            if (id.equals(successResult.getData())) {
                EventBus.getDefault().post(new GlobalFollowUserEvent(successResult.getData(), !postAdapter.getData().get(i).isFollow()));
                break;
            }
        }
    }

    @Override
    public void onDoFollowPersonFailure(BaseModel<Object> failureResult) {
        showToast(failureResult.getResultInfo());
    }

    @Subscribe
    public void onGlobalLikePostEvent(GlobalLikePostEvent event) {
        if (event != null && !StringUtils.isTrimEmpty(event.getPostId())) {
            for (int i = 0; i < postAdapter.getData().size(); i++) {
                String id = postAdapter.getData().get(i).getId();
                if (id.equals(event.getPostId())) {
                    postAdapter.getData().get(i).setLike(event.isLiked());
                    postAdapter.getData().get(i).setLikenum(postAdapter.getData().get(i).getLikenum() + (event.isLiked() ? 1 : -1));
                    postAdapter.notifyItemChanged(i);
                    break;
                }
            }
        }
    }

    @Subscribe
    public void onGlobalPostAppraiseEvent(GlobalPostAppraiseEvent event) {
        if (event != null && !StringUtils.isTrimEmpty(event.getPostId())) {
            for (int i = 0; i < postAdapter.getData().size(); i++) {
                String id = postAdapter.getData().get(i).getId();
                if (id.equals(event.getPostId())) {
                    postAdapter.getData().get(i).setCommentNum(event.getNum());
                    postAdapter.notifyItemChanged(i);
                    break;
                }
            }
        }
    }

    @Subscribe
    public void onGlobalFollowUserEvent(GlobalFollowUserEvent event) {
        if (event != null && !StringUtils.isTrimEmpty(event.getUserId())) {
            for (int i = 0; i < postAdapter.getData().size(); i++) {
                String id = postAdapter.getData().get(i).getAuthorId();
                if (id.equals(event.getUserId())) {
                    postAdapter.getData().get(i).setFollow(event.isFollow());
                    postAdapter.notifyItemChanged(i);
                }
            }
        }
    }


}
